sugarfreeControllers.controller('CourseController', ['$scope','$log','$filter', '$http' , '$timeout','HttpService','Utils','DictionarySerivce','QINIU',function($scope,$log,$filter, $http,$timeout,httpService,Utils,dictionarySerivce,QINIU) {
	"use strict";
	$scope.retrieveCourses = function(classTypeV) {tabSwitch(classTypeV);retrieveCourses(classTypeV); $scope.errMsg={};};
	
	$scope.createForm = function(){createForm(); $scope.errMsg={};};
	
	$scope.unCreateForm = function(){unCreateForm(); $scope.errMsg={};};
	
	$scope.editForm = function(){editForm();$scope.errorMsg={};};
	
	$scope.unEditForm = function(){unEditForm(); $scope.errMsg={};};
	
	$scope.reUnEditForm = function(){reUnEditForm(); $scope.errMsg={};};
	
	$scope.unViewForm = function(){unViewForm(); $scope.errMsg={};};
	
	$scope.deleteForm = function(){deleteForm(); $scope.errMsg={};};
	
	$scope.unDeleteForm = function(){unDeleteForm();$scope.errMsg={};};

	$scope.selectCourse = function($event,course_id) {selectCourse($event,course_id);$scope.errMsg={};};
	
    $scope.getPrices = function(classTypeV){getPrices(classTypeV);$scope.errMsg={};};
    
    $scope.getSports = function(classTypeV){getSports(classTypeV);$scope.errMsg={};};
    
    $scope.tabSwitch = function(classTypeV){tabSwitch(classTypeV);$scope.errMsg={};};
    
	$scope.clearFields = function() {clearFields();};
	
	$scope.createCourse = function(){createCourse();};
	
    $scope.updateCourse = function(){updateCourse();};
    
    $scope.deleteCourse = function(course){deleteCourse(course);};
    
    $scope.delCourseImage = function(fileId,type){delCourseImage(fileId,type);};
    
    $scope.delOriginCourseImage = function(index,fileId){delOriginCourseImage(index,fileId);};
    
    function retrieveCourses(classTypeV) {
      Utils.setProcessParclose(true);
      dictionarySerivce.queryCourses(classTypeV).then(function(resp){
    	  $scope.courses = resp.data;
    	  angular.forEach($scope.courses, function(course){
              if (course.classType.value === 1 || course.classType.value === 3) {
            	course.sport = course.sport || {};
                course.sport.name = course.classType.name;
              }
          });
          console.info("$scope.courses",$scope.courses);
    	  Utils.setProcessParclose(false);	  
      },function(resp){
    	  Utils.setProcessParclose(false);
      });
    }
    
    function createForm(){
    	Utils.setParclose(true);
    	$scope.page.useCreate = true;
    }
    
    function unCreateForm(){
    	$scope.course = {};
    	$scope.courseAddImages = [];
    	$scope.page.useCreate = false;
    	Utils.setParclose(false);
    }
    
    function editForm(){
    	$scope.selectedCourse = angular.copy($scope.originCourse);
    	$scope.page.useEdit=true;
    }
    
    function unEditForm(){
    	if(Utils.equals($scope.selectedCourse,$scope.originCourse)){
    		$scope.page.useEdit = false;
    		$scope.courseEditImages = [];
    		return ;
    	}
    	$scope.page.useOffEditConfirm = true;
    }
    
    function reUnEditForm(){
    	$scope.courseEditImages = [];
    	$scope.page.useOffEditConfirm = false;
    	$scope.page.useEdit = false;
    }
    
    function unViewForm(){
    	$scope.selectedCourse=null;
    	Utils.setParclose(false);
    }
    
    function deleteForm(){
    	Utils.setTopParclose(true);
    	$scope.page.useDelConfirm=true;
    }
    
    function unDeleteForm(){
    	$scope.page.useDelConfirm=false;
    	Utils.setTopParclose(false);
    }
    
    
    
    $scope.originCourse = null;
    function selectCourse($event, course_id) {
      var found = $filter('filter') ($scope.courses, {id: course_id}, true);
      if (found.length ) {
        // unselect 
        if ( Utils.isUndefinedOrNull($scope.selectedCourse) || $scope.selectedCourse.id !== found[0].id){
          $scope.originCourse = angular.copy(found[0]);
          $scope.selectedCourse = angular.copy(found[0]);
          Utils.setParclose(true);
        }
        else {
          $scope.selectedCourse = null;
        }
      }else {
        $scope.selectedCourse = null;
      }
      $event.stopPropagation();
    }
    
    function getPrices(classTypeV){
		dictionarySerivce.getPrices(classTypeV).success(function(data){
	    	  $scope.prices = data;
		          angular.forEach($scope.prices, function(price){
		        	  price.priceText = " X " + price.price;
		          });
			});
    }
    
    function getSports(classTypeV){
		dictionarySerivce.getSports(classTypeV).success(function(data){
			$scope.sports = data;
		});
    }
    
    function tabSwitch(classTypeV){
    	$scope.initVal.classTypeV = classTypeV || $scope.initVal.classTypeV;
    	//$scope.course.classTypeV = classTypeV;
    	getPrices($scope.initVal.classTypeV);
    	getSports($scope.initVal.classTypeV);
    }
	
	
    
    
    //create course info
    function createCourse() {
    	var valid = true;
    	$scope.course = $scope.course || {};
    	if (!$scope.course.classTypeV){
    		$scope.errMsg.emptyClassType = $scope.msg.emptyClassType;
    		valid = false;
    	}else{
    		$scope.errMsg.emptyClassType = "";
    	}
    	if (!$scope.course.sportV) {
    		$scope.errMsg.emptySporttype = $scope.msg.emptySporttype;
            valid = false;
        }else{
            $scope.errMsg.emptySporttype = "";
        }
    	if (typeof($scope.course.priceInt)==='undefined'){
    		$scope.errMsg.emptyPrice = $scope.msg.emptyPrice;
            valid = false;
	    }else{
	    	$scope.errMsg.emptyPrice = "";
	    }
    	
    	if (!$scope.course.title){
    		$scope.errMsg.emptyTitle = $scope.msg.emptyTitle;
            valid = false;
        }else{
        	$scope.errMsg.emptyTitle = "";
        }
    	if(valid){
    		Utils.setProcessParclose(true);
	        var _queryCreateCourse = "course/create";
	        $scope.course.classTypeV = $scope.course.classTypeV || $scope.initVal.classTypeV;
	        var _dataStr = "title=" + $scope.course.title + 
	                "&description=" + (typeof($scope.course.description)==="undefined"?"":$scope.course.description) +
	                "&priceInt="+$scope.course.priceInt +
	        		"&classType="+$scope.course.classTypeV +
	        		"&sportType="+$scope.course.sportV;
	        
	        var images = $scope.courseAddImages
	        var _imgStr = "";
	        for(var i=0 ; i < $scope.courseAddImages.length ; i++){
	        	_imgStr +="&images=" + $scope.courseAddImages[i].key;
	        }
	        _dataStr += _imgStr;
			
			console.error("_dataStr",_dataStr);
			
	        var _urlCreateCourse = $scope.apiUrl + _queryCreateCourse;
	        
	        if($scope.log.debug){
	        	$log.info("create%sUrl=>",'课程信息',_urlCreateCourse,_dataStr);
	        }
	        $http ({
	              method: 'POST',
	              url: _urlCreateCourse,
	              data: _dataStr,
	              headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
	        }).
	          then(function(response) {
	            alert("课程信息保存成功");
	            $scope.course = {};
	            $scope.courseAddImages = [];
	            $scope.page.useCreate = false;
	            Utils.setProcessParclose(false);
	            Utils.setParclose(false);
	            retrieveCourses($scope.initVal.classTypeV);
	          }, function(response){
	            alert("课程信息保存失败");
	            Utils.setProcessParclose(false);
	            console.log('create course failed', response.data);
	          });
    	}
    }
    
    function updateCourse() {
      var valid = true;
      if (!$scope.selectedCourse.sport.value){
    	  $scope.errMsg.emptySporttype = $scope.msg.emptySporttype;
    	  valid = false;
      }else{
    	  $scope.errMsg.emptySporttype = "";
      }
      
      if (!$scope.selectedCourse.priceInt) {
    	  console.log($scope.selectedCourse.priceInt);
    	  $scope.errMsg.emptyPrice = $scope.msg.emptyPrice;
    	  valid = false;
      }else{
    	  $scope.errMsg.emptyPrice = "";
	  }
      
      if (!$scope.selectedCourse.title) {
    	  $scope.errMsg.emptyTitle = $scope.msg.emptyTitle;
    	  valid = false;
      }else{
    	  $scope.errMsg.emptyTitle = "";
	  }
      
      if(valid){
    	  Utils.setProcessParclose(true);
    	  var _queryUpdateCourse = "course/edit";
    	  $scope.selectedCourse.classType.value = $scope.selectedCourse.classType.value || $scope.initVal.classTypeV;
    	  var _dataStr = "id=" + $scope.selectedCourse.id + 
    	  "&title=" + $scope.selectedCourse.title + 
    	  "&description=" + $scope.selectedCourse.description +
    	  "&classType=" + $scope.selectedCourse.classType.value +
    	  "&sportType=" + $scope.selectedCourse.sport.value +
    	  "&priceInt=" + $scope.selectedCourse.priceInt;
    	  
    	  var _imgStr = "";
    	  console.error("courseEditImages",$scope.courseEditImages);
    	  for(var i=0 ; i < $scope.courseEditImages.length ; i++){
    	  	_imgStr +="&images=" + $scope.courseEditImages[i].key;
    	  }
    	  var _delImgStr = "";
    	  if($scope.selectedCourse.deletedImages){
    	  	for(var i=0 ; i < $scope.selectedCourse.deletedImages.length ; i++){
    	  		_delImgStr +="&deletedImages=" + $scope.selectedCourse.deletedImages[i];
    	  	}
    	  }
	      _dataStr += _imgStr;
	      _dataStr += _delImgStr;
    	  
    	  var _urlUpdateCourse = $scope.apiUrl + _queryUpdateCourse;
    	  
    	  if($scope.log.debug){
    		  $log.info("修改%s","课程",_urlUpdateCourse,_dataStr);
    	  }
    	  $http ({
    		  method: 'POST',
    		  url: _urlUpdateCourse,
    		  data: _dataStr,
    		  headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
    	  }).
    	  then(function(response) {
    		  if(response.status === 200){
    			  alert("课程信息保存成功");
    			  $scope.page.useEdit = false;
    			  Utils.setParclose(false);
    			  Utils.setProcessParclose(false);
    			  $scope.courseEditImages = [];
    			  //Utils.setParclose(false);
    			  $scope.retrieveCourses($scope.selectedCourse.classType.value);
    			  $scope.clearFields();
    		  }
    	  }, function(response){
    		  alert("课程信息保存失败");
    		  Utils.setProcessParclose(false);
    	  });
      }
    }
    
    
    //deleteCourse
    function deleteCourse(course){
    	 course.classType.value = course.classType.value || $scope.initVal.classTypeV;
    	 $scope.initVal.classTypeV = course.classType.value;
    	 var _delCourse = "course/delete?courseId=" + course.id +
    	 				  "&classType=" + course.classType.value;
    	 var _urlDelCourse = $scope.apiUrl + _delCourse;
    	 if($scope.log.debug){
    		 $log.info("delete%surl=>","课程信息",_urlDelCourse);
    	 }
    	 Utils.setProcessParclose(true);
		 $http.get(_urlDelCourse).success(function(data){
			if(data.errCode === "8000"){
				alert("删除课程成功！！！");
				 Utils.setProcessParclose(false);
			}else{
				alert("删除课程失败！！！");
			}
		    $scope.retrieveCourses($scope.initVal.classTypeV);
		    $scope.page.useDelConfirm = false;
		    Utils.setTopParclose(false);
		    $scope.page.useEdit=false;
		    $scope.selectedCourse=null;
		    Utils.setParclose(false);
		 });
    }
    
    
    function delCourseImage(fileId,type){
    	console.error(fileId,type);
    	if(type === 'Add'){
    		delCourseAddImage(fileId);
    	}else{
    		delCourseEditImage(fileId);
    	}
    }
    
    function delCourseAddImage(fileId){
	  	$scope.courseAddImages = removeElementInArray($scope.courseAddImages,fileId);
    }
    
    function delCourseEditImage(fileId){
	  	$scope.courseEditImages = removeElementInArray($scope.courseEditImages,fileId);
    }
    
    function removeElementInArray(array,fileId){
    	console.info("fileId:",array.length);
    	var _array = [];
    	for(var i = 0; i< array.length ; i++){
    		console.info(i+":",array[i]);
    		if(array[i]['id'] !== fileId){
    			_array.push(array[i]);
    		}
    	}
    	return _array;
    }
    
    function delOriginCourseImage(index,fileId){
//  	httpService.get("course/image/delete?id=" + fileId)
//  		.then(function(rsps){
//  			if(rsps.data.errCode === "8000"){
    				$scope.selectedCourse.images.splice(index, 1);
    				//$scope.originCourse.images.splice(index, 1);
    				$scope.selectedCourse.deletedImages = $scope.selectedCourse.deletedImages || [];
    				$scope.selectedCourse.deletedImages.push(fileId);
//  				console.log('delete image success!');
//  			}else{
//  				alert('图片删除出错');
//  			}
//  		},function(rsps){
//  			console.error('图片删除出错！');
//  			alert('图片删除出错');
//  		});
    }
    
    
    
    function clearFields() {
    	$scope.course = null;
    	$scope.priceInt= null;
    	$scope.prices = {};
    	$scope.selectedCourse = null;
    }
    
    function initData(){
    	//control page box
    	$scope.page = {
    			useCreate:false,
    			useEdit:false,
    			useDelConfirm:false,
    			useOffEditConfirm:false
    	};
    	
    	//default value
    	$scope.initVal = {
    		classTypeV : 2
    	};
    	
    	//sports
    	dictionarySerivce.getSports($scope.initVal.classTypeV).success(function(data){
      	  $scope.sports = data;
		});
    	
    	//prices
    	dictionarySerivce.getPrices($scope.initVal.classTypeV).success(function(data){
        	  $scope.prices = data;
  	          angular.forEach($scope.prices, function(price){
  	        	  price.priceText = " X " + price.price;
  	          });
  		});
    	
    	$scope.msg={
    			emptySporttype:"错误：请选择课程项目",
    			emptyPrice:"错误：请选择价格",
    			emptyTitle:"错误：请填写课程名称",
    			emptyClassType:"错误：请选择课程类型"
    	};
    	$scope.errMsg = {};
    	
    	$scope.tabs = [{header:"团体课"},{header:"私教课"},{header:"自由课"}];
    	
    	//debug
    	$scope.log={
    		debug:true
    	};
    	
    	//init course classType value
    	$scope.course = {
    		classTypeV:2
    	};
    	
    	$scope.qiniuDomain = QINIU.domain;
    	$scope.courseAddImages = [];
    	$scope.courseEditImages = [];
    	
    }
    initData();
}]);